package com.ziJing.multithreading.sync.interview01;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @program Multithreading
 * @description:
 * @author: zhangbo
 * @create: 2022/05/03 23:56
 */
public class T05_CountDownLatch {

    List<Object> list = Collections.synchronizedList(new LinkedList<>());


    int size() {
        return list.size();
    }


    void add(Object ele) {
        list.add(ele);
    }


    Object get(int index) {
        return list.get(index);
    }


    public static void main(String[] args) {

        T05_CountDownLatch c = new T05_CountDownLatch();

        CountDownLatch latch  = new CountDownLatch(1);

        new Thread(() -> {
            System.out.println("t2 启动");
            if (c.size() != 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("t2 结束");


        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");
            for (int i = 0; i < 10; i++) {
                c.add(new Object());
                System.out.println("add " + i);

                if (c.size() == 5) {
                    latch.countDown();

                }

//              如果这里注释掉，会怎么样，怎么解决？
//              用两个CountDownLatch
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "t1").start();
    }
}
